// 监听输入和参数变化，生成二维码
const input = document.getElementById('qr-input');
const sizeInput = document.getElementById('qr-size');
const levelInput = document.getElementById('qr-level');
const qrCodeDiv = document.getElementById('qr-code');
const downloadBtn = document.getElementById('download-btn');
const foregroundInput = document.getElementById('qr-foreground');
const backgroundInput = document.getElementById('qr-background');
const marginInput = document.getElementById('qr-margin');
const getUrlBtn = document.getElementById('get-url-btn');
const clearInputBtn = document.getElementById('clear-input-btn');

let qr = null;

function generateQRCode() {
  const text = input.value.trim();
  const size = parseInt(sizeInput.value, 10) || 200;
  const level = levelInput.value;
  const colorDark = foregroundInput.value || '#000000';
  const colorLight = backgroundInput.value || '#ffffff';
  const margin = parseInt(marginInput.value, 10) || 4;
  qrCodeDiv.innerHTML = '';
  if (!text) return;
  qr = new QRCode(qrCodeDiv, {
    text,
    width: size,
    height: size,
    colorDark,
    colorLight,
    correctLevel: QRCode.CorrectLevel[level],
    margin: margin
  });
}

input.addEventListener('input', generateQRCode);
sizeInput.addEventListener('input', generateQRCode);
levelInput.addEventListener('change', generateQRCode);
foregroundInput.addEventListener('input', generateQRCode);
backgroundInput.addEventListener('input', generateQRCode);
marginInput.addEventListener('input', generateQRCode);

downloadBtn.addEventListener('click', function() {
  if (!qr) return;
  const canvas = qrCodeDiv.querySelector('canvas');
  const img = qrCodeDiv.querySelector('img');
  let url = '';
  if (canvas) {
    url = canvas.toDataURL('image/png');
  } else if (img) {
    url = img.src;
  } else {
    return;
  }
  const a = document.createElement('a');
  a.href = url;
  a.download = 'qrcode.png';
  a.click();
});

getUrlBtn.addEventListener('click', function() {
  // 获取当前激活标签页的网址
  if (chrome && chrome.tabs) {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      if (tabs && tabs[0] && tabs[0].url) {
        input.value = tabs[0].url;
        generateQRCode();
      }
    });
  } else {
    // 兼容非扩展环境
    input.value = window.location.href;
    generateQRCode();
  }
});

clearInputBtn.addEventListener('click', function() {
  input.value = '';
  generateQRCode();
});

generateQRCode(); 